/**
 * 
 */
package io.potato.notify.controller;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.potato.core.util.SmsUtil;
import io.potato.core.web.BaseController;
import io.potato.ts.domain.SmsStatusReport;
import io.potato.ts.domain.SmsUpRecord;
import io.potato.ts.service.SmsStatusReportService;
import io.potato.ts.service.SmsUpRecordService;
import io.potato.ts.sms.SmsApiStatus;
import lombok.extern.slf4j.Slf4j;

/**
 * 接收华为短信回调
 * @author timl
 * created: 2019年1月9日 下午2:28:44
 */
@RestController
@Slf4j
public class SmsNotifyController extends BaseController {
	
	static final String SUCCESS = "SUCCESS";
	
	@Autowired
	SmsStatusReportService ssrs;
	
	@Autowired
	SmsUpRecordService surs;
	
	ExecutorService poolExecutor = Executors.newFixedThreadPool(150);
	
	static final String CODE = "0";
	
	static final String DELIVRD = "DELIVRD";
	
	/**
	 * 接收短信平台主动发送的短信状态报告
	 * @param smsMsgId  发送短信成功时返回的短信唯一标识
	 * @param total  长短信拆分后的短信条数
	 * @param sequence  长短信拆分后的短信序号
	 * @param status  短信状态报告枚举值：l DELIVRD：用户已成功收到短信  其他失败
	 * @param orgCode 透传南向网元返回的状态码
	 * @param source  短信状态报告来源  1：短信平台自行产生的状态报告 2：短信网关返回的状态报告
	 * @param extend 扩展字段，由客户在发送短信的请求中携带。若客户发送短信时未携带extend参数，则状态报告中也不会携带extend参数
	 * @param to 本条状态报告对应的短信的接收方号码，仅当状态报告中携带了extend参数时才会同时携带该参数
	 * @return
	 */
	@RequestMapping("/notify/receiveStatusReport")
	public String receiveStatusReport(
			 @RequestParam(name="smsMsgId", required=true) String smsMsgId, 
			 @RequestParam(name="total",    required=false, defaultValue="1") Integer total, 
			 @RequestParam(name="sequence", required=false, defaultValue="1") Integer sequence, 
			 @RequestParam(name="status",   required=true)  String status,
			 @RequestParam(name="orgCode",  required=false) String orgCode,
			 @RequestParam(name="source",  required=false) Integer source,
			 @RequestParam(name="extend",   required=false, defaultValue="") String extend,
			 @RequestParam(name="to",       required=false) String to) {
		
		if (total > 1 && sequence > 1) {
			// 长短信只接收第一条短信的短信报告， 后面的忽略
			return SUCCESS;
		}
		
		try {
			SmsStatusReport report = new SmsStatusReport();
			//report.setMsgId(smsService.getMsgId(smsMsgId));
			report.setHwMsgId(smsMsgId);
			report.setTotal(total);
			report.setStatus(SmsApiStatus.getReceiveStatus(status));
			report.setStatusDesc(status);
			report.setOrgCode(orgCode);
			report.setSource(source);
			report.setDestNum(to);
			report.setReadStatus(0);
			
			report.setSenderType(0);
			report.setExtendCode(CODE);
			
			if (!StringUtils.isEmpty(extend)) {
				String[] arr = extend.split("_");
				if (arr.length == 5) {
					Integer senderType = "1".equals(arr[0]) ? 1 : 2;
					report.setSenderType(senderType);
					report.setUserCode(arr[1]);
					report.setBatchCode(arr[2]);
					report.setExtendCode(arr[3]);
					
					Integer needReport = "1".equals(arr[4]) ? 1 : 0;
					report.setNeedReport(needReport);
				}
			} 
			
			poolExecutor.execute(() -> {
				try {
					ssrs.receive(report);
				} catch (Exception e) {
					log.error(e.getMessage());
				}
			});
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return SUCCESS;
	}
	
	/**
	 * 接收上行短信
	 * @param smsMsgId  发送短信成功时返回的短信唯一标识
	 * @param from  上行短信发送方的号码。
	 * @param to 上行短信接收方的号码。
	 * @param body  上行短信发送的内容。
	 * @return
	 */
	@PostMapping("/notify/receiveUpSms")
	public String receiveUpSms(
			@RequestParam(name="smsMsgId") String smsMsgId,
			@RequestParam(name="from")     String from,
			@RequestParam(name="to")       String to,
			@RequestParam(name="body")     String body) {
		
		
		try {
			from = SmsUtil.trimPhoneNumber(from);
			SmsUpRecord sms = new SmsUpRecord();
			sms.setContent(body);
			sms.setHwMsgId(smsMsgId);
			sms.setFromNum(from);
			sms.setDestNum(to);
			sms.setExtendCode(to.length() > 12 ? to.substring(12) : "0"); // 号码格式如csms190108980143218 截取12位后面的为拓展码
			sms.setReadTimes(0);
			sms.setReceiveTime(LocalDateTime.now());
			sms.setStatus(0);
			
			surs.receive(sms);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		
		return SUCCESS;
	}

}
